export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

//通过秒转换时间
export const timeFilterToSeconds = (seconds: number) => {
  let ss: number | string = parseInt(seconds.toString()) // 秒
  let mm: number | string = 0 // 分
  let hh: number | string = 0 // 小时
  if (ss > 60) {
    mm = Number(parseInt((ss / 60).toString()))
    ss = parseInt((ss % 60).toString())
  }
  if (mm > 60) {
    hh = parseInt((mm / 60).toString())
    mm = parseInt((mm % 60).toString())
  }
  let result = ('00' + parseInt(ss.toString())).slice(-2)
  if (mm > 0) {
    result = ('00' + parseInt(mm.toString())).slice(-2) + ' : ' + result
  } else {
    result = '00 : ' + result
  }
  if (hh > 0) {
    result = ('00' + parseInt(hh.toString())).slice(-2) + ': ' + result
  }
  return result
}


/**
 * 验证手机号码
 * @param mobile
 * @returns boolean
 */
export const regMobile = (mobile: string) => {
  return /^1[3456789]\d{9}$/.test(mobile)
}
/**
 * 隐藏手机号中间几位
 * @param mobile 
 */
export const phoneHide = (mobile: string) => {
  const arr = mobile.split('')
  //從索引3開始刪除5個長度，添加5個*137*****050
  arr.splice(3, 5, '*****')
  return arr.join('')
}

//判断昵称是否包含特殊符号
export function isNicknameValid(nickname: string): boolean {
  let specialChars = "!@#$%^&*()_+{}|:\"<>?`~-=\\;'[]\/,.'";
  /**
   * 验证昵称是否包含特殊字符。
   *
   * @param nickname 用户输入的昵称。
   * @returns 如果昵称不包含特殊字符，返回 true；否则返回 false。
   */
  const specialCharsPattern = /[!@#$%^&*()\-_=+{};:,<.>]/g;
  return !specialCharsPattern.test(nickname);
}


//取map数组中最大值
export const getMapMax = (list: Map<string, number>) => {
  let index = 0
  let text = ''
  for (let [key, val] of list.entries()) {
    if (index <= val) {
      text = key
    }
  }
  return text
}

//map 转数组
export const mapToArray = (list: Map<string, number>): string[] => {
  let text = []
  for (let [key, val] of list.entries()) {
    text.push(key)
  }
  return text
}

//判断字符串是否可以转JSON
export const isJSON = (str: string) => {
  try {
    JSON.parse(str)
  } catch (e) {
    // 转换出错，抛出异常
    return false
  }
  return true
}

//判断当前是否是直辖市

export const isMunicipality = (regionId: string) => {
  if ([82, 81, 11, 12, 31, 50].includes(Number(regionId.slice(0, 2)))) {
    return true
  } else {
    return false
  }
}